<?php
namespace app\controller\admin\system\auth;

use app\BaseController;
use app\common\repositories\system\SystemRoleRepository as repository;
use app\validate\admin\RoleValidate;
use think\App;

class Role extends BaseController
{
    protected repository $repository;
    protected string $type = 'admin';

    public function __construct(App $app, repository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }


    public function createForm()
    {
        return app('json')->success(formToData($this->repository->form($this->type)));
    }


    public function updateForm($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->updateForm($this->type, $id)));
    }


    public function getList()
    {
        [$page, $limit] = $this->page();
        return app('json')->success($this->repository->search($this->type, [], $page, $limit));
    }

    public function get($id)
    {
        $data = $this->repository->get($id);
        return app('json')->success($data);
    }

    public function switchStatus($id)
    {
        $status = $this->request->param('status');
        if (!$this->repository->mExists($this->type, $id))
            return app('json')->fail('数据不存在');
        $this->repository->update($id, ['status' => $status == 1 ? 1 : 0]);
        return app('json')->success('编辑成功');
    }

    public function delete($id)
    {
        if (!$this->repository->mExists($this->type, $id))
            return app('json')->fail('数据不存在');
        $this->repository->delete($id);
        return app('json')->success('删除成功');
    }

    public function create(RoleValidate $validate)
    {
        $data = $this->checkParam($validate);
        $data['type'] = $this->type;
        $this->repository->create($data);
        return app('json')->success('添加成功');
    }

    public function update($id, RoleValidate $validate)
    {
        $data = $this->checkParam($validate);
        if (!$this->repository->mExists($this->type, $id))
            return app('json')->fail('数据不存在');
        $this->repository->update($id, $data);
        return app('json')->success('编辑成功');
    }


    private function checkParam(RoleValidate $validate)
    {
        $data = $this->request->params(['role_name', ['rules', []], ['status', 0]]);
        $validate->check($data);
        return $data;
    }
}
